import { app, BrowserWindow, ipcMain, dialog, session, shell } from 'electron/main'
import fs from 'fs-extra';
import path from 'path';
import fetch from 'node-fetch';
import AdmZip from 'adm-zip';

const downloadCore = (win, ipcMain) => {
    ipcMain.on("download-browser", async (event, text) => {
        const userDataDir = app.getPath('userData');
        const zipPath2 = path.join(userDataDir, `sdk/cache/${text.type}`)
        let url = text.url

        if (!fs.existsSync(zipPath2)) {
            fs.mkdirSync(zipPath2, { recursive: true });
        }
        const zipPath = path.join(zipPath2, `${text.version}.zip`)
        console.log(zipPath);
        
        try {
            // 下载文件
            const response = await fetch(url)
            const totalBytes = parseInt(response.headers.get('content-length'), 10)
            let receivedBytes = 0

            const fileStream = fs.createWriteStream(zipPath)
            response.body.pipe(fileStream)

            // 发送下载进度
            response.body.on('data', (chunk) => {
                receivedBytes += chunk.length
                win.webContents.send('on-download-browser', {
                    type: text.type,
                    version: text.version,
                    status: 0,
                    progress: Math.round((receivedBytes / totalBytes) * 100)
                })
            })

            // 等待下载完成
            await new Promise((resolve, reject) => {
                fileStream.on('finish', resolve)
                fileStream.on('error', reject)
            })

            // 解压文件
            const zip = new AdmZip(zipPath)
            zip.extractAllTo(`${zipPath2}/${text.version}`, true)

            // 删除压缩包
            await fs.remove(zipPath)

            win.webContents.send('on-download-browser', {
                type: text.type,
                version: text.version,
                status: 1,
                progress: 100
            })

            return { success: true, path: zipPath2 }
        } catch (error) {
            await fs.remove(zipPath).catch(() => { })
            throw new Error(`操作失败: ${error.message}`)
        }
    })
};

export default downloadCore;
